/*
 * @Author: wuyuxin
 * @Date: 2022-04-16 00:54:32
 * @LastEditors: wuyuxin
 * @LastEditTime: 2022-04-29 16:30:41
 * @Description:
 */
import { Module } from 'vuex'
import { LoginModuleState } from './type'
import { IRootStore } from '../type'

import {
  handleLogin,
  getUserInfoById,
  getMenuListByRoleId
} from '@/api/login/login'
import localCache from '@/utils/cache'
import { handleUserMenu, mapMenusToPermissions } from '@/utils/map-menus'
import router from '@/router'

const loginModule: Module<LoginModuleState, IRootStore> = {
  namespaced: true,
  state() {
    return {
      id: '',
      token: '',
      userInfo: {},
      userMenus: [],
      permissions: []
    }
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus

      console.log('注册动态路由')

      // userMenus => routes
      const routes = handleUserMenu(userMenus)
      console.log(routes, '=================', userMenus)
      // 将routes => router.main.children
      routes.forEach((route) => {
        router.addRoute('main', route)
      })

      // 获取用户按钮的权限
      const permissions = mapMenusToPermissions(userMenus)
      state.permissions = permissions
    }
  },
  actions: {
    async handleLoginAction({ commit, dispatch }, payload) {
      const data = {
        name: payload.userName,
        password: payload.password
      }
      // 1.实现登录逻辑
      const loginResult = await handleLogin(data)
      const { id, token } = loginResult.data
      commit('changeToken', token)
      localCache.setCache('token', token)

      dispatch('getInitialDataAction', null, { root: true })
      // 2.请求用户信息
      const userInfoResult = await getUserInfoById(id)
      const userInfo = userInfoResult.data
      commit('changeUserInfo', userInfo)
      localCache.setCache('userInfo', userInfo)

      // 3.请求用户菜单
      const userMenusResult = await getMenuListByRoleId(userInfo.role.id)
      const userMenus = userMenusResult.data
      commit('changeUserMenus', userMenus)
      localCache.setCache('userMenus', userMenus)

      // 4.跳到首页
      router.push('/main')
    },
    loadLocalLogin({ commit, dispatch }) {
      const token = localCache.getCache('token')
      if (token) {
        commit('changeToken', token)
        dispatch('getInitialDataAction', null, { root: true })
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const userMenus = localCache.getCache('userMenus')
      if (userMenus) {
        commit('changeUserMenus', userMenus)
      }
    }
  },
  modules: {}
}

export default loginModule
